//
//  HttpBaseAction.m
//  Training
//
//  Created by michael shen on 15/6/17.
//  Copyright (c) 2015年 coolem. All rights reserved.
//

#import "HttpBaseAction.h"
#import "HttpBaseClient.h"
#import "JsonParser.h"

@implementation HttpBaseAction

+ (void)requestWithRequest:(NSString *)request jsonParserSelector:(SEL)selector finish:(HTTPResultBlock)block{
    [self requestWithRequest:request jsonTarget:[JsonParser defaultParser] jsonSelector:selector finish:block];
    
}

+ (void)requestWithRequest:(NSString *)request jsonTarget:(id)target jsonSelector:(SEL)selector finish:(HTTPResultBlock)block{
    [self requestWithRequest:request method:@"POST" jsonTarget:target jsonSelector:selector finish:block];
}

+ (void)requestWithRequest:(NSString *)request method:(NSString *)method jsonTarget:(id)target jsonSelector:(SEL)selector finish:(HTTPResultBlock)block{
    [[HttpBaseClient sharedClient] requestWithRequest:request method:method finish:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self finishWithOperation:operation error:error target:target action:selector finish:block];
    }];
}

+ (void)finishWithOperation:(AFHTTPRequestOperation *)operation error:(NSError *)error target:(id)target action:(SEL)selector finish:(HTTPResultBlock)block{
    NSLog(@"Request:%@ \nResponse:%@",operation.request.URL.absoluteString,operation.responseString);
    if ([target respondsToSelector:selector]) {
        id result = [target performSelector:selector withObject:operation.responseData];
        if (selector == @selector(getResultWithResponseData:) && target == [JsonParser defaultParser]) {
            
            if (result != nil) {
                error = result;
            }
        }else {
            if (result == nil && error == nil) {
                error = [[JsonParser defaultParser] getResultWithResponseData:operation.responseData];
            }
        }
        block(result,error);
    }
    else {
        if (error == nil) {
            error = [[JsonParser defaultParser] getResultWithResponseData:operation.responseData];
        }
        block(operation,error);
    }
}

@end
